package com.yizisu.basemvvm.utils.permission

import android.content.Intent
import android.content.pm.PackageManager
import androidx.core.app.ActivityCompat
import com.yizisu.basemvvm.app

/**
 * 获取权限工具类
 * 任何地方都可以调用
 */
object PermissionUtil {
    internal var permissionListener: Function1<List<String>, Unit>? = null
    internal var requestPermissions: MutableList<String>? = null

    /**
     * 请求权限
     * permissionListener 被拒绝的权限监听，为空则获取全部权限
     */
    fun request(permission: List<String>, permissionListener: Function1<List<String>/*被拒绝的权限集合*/, Unit>) {
        //没有权限
        val unGetPermission = check(permission)
        if (unGetPermission.isNotEmpty()) {
            this.permissionListener = permissionListener
            this.requestPermissions = unGetPermission
            app.startActivity(Intent(app, PermissionActivity::class.java).apply {
                flags = Intent.FLAG_ACTIVITY_NEW_TASK
            })
        } else {
            permissionListener.invoke(listOf())
        }
    }

    /**
     * 检查是否获取到了某权限
     * 返回值，true 有了该权限
     * false 没有此权限
     */
    fun check(permission: String): Boolean {
        return ActivityCompat.checkSelfPermission(app, permission) == PackageManager.PERMISSION_GRANTED
    }

    /**
     * 检查是否获取到了某权限
     * 返回值，没有获得权限的集合
     */
    fun check(permissions: List<String>): MutableList<String> {
        val unGetPermissions = mutableListOf<String>()
        permissions.forEach {
            if (!check(it)) {
                unGetPermissions.add(it)
            }
        }
        return unGetPermissions
    }
}